package cn.softgame.cms.secure.user.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.softgame.cms.common.page.domain.PageResultBean;
import cn.softgame.cms.common.security.TissonDESPasswordEncoder;
import cn.softgame.cms.open.common.service.CommonService;
import cn.softgame.cms.secure.organization.domain.OrganizationBean;
import cn.softgame.cms.secure.organization.service.IOrgService;
import cn.softgame.cms.secure.user.domain.User;
import cn.softgame.cms.secure.user.domain.UserOrgData;
import cn.softgame.cms.secure.user.domain.UserResData;
import cn.softgame.cms.secure.user.service.UserService;
import freemarker.ext.beans.MapModel;



/**
 * 用户管理配置控制器
 * @author yangying
 * 2013-4-9
 */
@Controller
@RequestMapping("/secure/user/*")
public class QueryUserController {

	
	@Autowired(required=true)
	private IOrgService orgService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CommonService commonService;

	@RequestMapping(value="initUser.html")
	public ModelAndView initUser(){
		ModelAndView mav = new ModelAndView();
		mav.addObject("addUser",new User());
		mav.setViewName("secure/user/addUserForm");
		return mav;
	}
	
	@RequestMapping("listUsers.html")
	public ModelAndView listUsers() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("org",orgService.queryOrgByOrgId("1"));
		//mav.addObject("users", userService.queryAllUsers(user));
		mav.addObject("user",new User());
		mav.setViewName("secure/user/queryUser");
		return mav;
	}
	
	@RequestMapping("loadUserOrgsData.html")
	public @ResponseBody List<OrganizationBean> loadUserOrgsData(){
		List<OrganizationBean> list = orgService.loadOrgsData();
		// 去掉parentSysOrg
		for(OrganizationBean m : list){
			m.setParentSysOrg(null);
		}
		return list;
	}
	
	@RequestMapping("queryUserOrgByOrgId.html")
	public ModelAndView queryOrgByOrgId(@RequestParam String orgId) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("org", orgService.queryOrgByOrgId(orgId));
		mav.setViewName("secure/user/queryUser");
		return mav;
	}	
	
	@RequestMapping(value="loadAllUsers.html")
	public @ResponseBody PageResultBean loadAllUsers(Integer jtStartIndex,Integer jtPageSize,String orgId,String userName,String loginName){
		PageResultBean pr = new PageResultBean();
		try {
			User user = new User();
			user.setOrgId(orgId);
			user.setUserName(userName);
			user.setLoginName(loginName);
			user.setFromNumber(jtStartIndex);
			user.setToNumber(jtStartIndex+jtPageSize);
			pr.setResult("OK");
			pr.setRecords(userService.queryAllUsers(user));
			pr.setTotalRecordCount(userService.userCount(user));
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
		}
		
		return pr;
	}
	//保存
	@RequestMapping(value="saveUser.html")
	public @ResponseBody PageResultBean saveUser(User user,String orgIds,String resTreeIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(user!=null){
				String userId = user.getUserId();
				if(userId!=null && !"".equals(userId)){
					user.setUpdateDate(commonService.getDatabaseCurrentTime());
					user.setRoleId("");
					userService.updateUser(user);
					//修改组织授权
					if(orgIds!=null && !"".equals(orgIds)){
						String[] orgIdArray = orgIds.split(",");
						userService.deleteUserOrgData(userId);
						for(String orgId : orgIdArray){
							UserOrgData userOrgData = new UserOrgData();
							userOrgData.setUserOrgDataId(commonService.getCode());
							userOrgData.setUserId(user.getUserId());
							userOrgData.setOrgId(orgId);
							userService.saveUserOrgData(userOrgData);
						}
					}
					//修改资源授权
					if(resTreeIds!=null && !"".equals(resTreeIds)){
						String[] resTreeIdArray = resTreeIds.split(",");
						userService.deleteUserResData(userId);
						for(String resTreeId : resTreeIdArray){
							UserResData userResData = new UserResData();
							userResData.setUserResId(commonService.getCode());
							userResData.setUserId(user.getUserId());
							userResData.setResTreeId(resTreeId);
							userService.saveUserResData(userResData);
						}
					}
				}else{
					user.setUserId(commonService.getCode());
					user.setCreateDate(commonService.getDatabaseCurrentTime());
					user.setIsValid("Y");
					user.setTreeCode(commonService.getMaxTreeCode("SYS_USER", "tree_code", null, null));
					user.setRoleId("");
					if(user.getPassword() != null && !"".equals(user.getPassword().trim())){
						TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
						user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					}else{
						user.setPassword("1111");
						TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
						user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					}
					
					userService.saveUser(user);
					//保存组织授权
					if(orgIds!=null && !"".equals(orgIds)){
						String[] orgIdArray = orgIds.split(",");
						for(String orgId : orgIdArray){
							UserOrgData userOrgData = new UserOrgData();
							userOrgData.setUserOrgDataId(commonService.getCode());
							userOrgData.setUserId(user.getUserId());
							userOrgData.setOrgId(orgId);
							userService.saveUserOrgData(userOrgData);
						}
					}
					//保存资源授权
					if(resTreeIds!=null && !"".equals(resTreeIds)){
						String[] resTreeIdArray = resTreeIds.split(",");
						for(String resTreeId : resTreeIdArray){
							UserResData userResData = new UserResData();
							userResData.setUserResId(commonService.getCode());
							userResData.setResTreeId(resTreeId);
							userResData.setUserId(user.getUserId());
							userService.saveUserResData(userResData);							
						}
					}
				}
			}
			pr.setResult("OK");
			pr.setRecord(user);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("保存失败!");
		}
		return pr;
	}
	
	@RequestMapping(value="updateUser.html")
	public ModelAndView updateUser(String userId){
		ModelAndView mav = new ModelAndView();
		try{
			User user = userService.queryUserByUserId(userId);
			mav.addObject("addUser",user);
			
			List<UserOrgData> userOrgDataList = userService.queryUserOrgDataByUserId(userId);
			if(userOrgDataList!=null && userOrgDataList.size()>0){
				StringBuffer sb = new StringBuffer();
				for(UserOrgData uod : userOrgDataList){
					sb.append(uod.getOrgId()).append(",");
				}
				sb.deleteCharAt(sb.length()-1);
				mav.addObject("orgIds",sb.toString());
			}
			
			
			List<UserResData> userResDataList = userService.queryUserResDataByUserId(userId);
			if(userResDataList!=null && userResDataList.size()>0){
				StringBuffer ub = new StringBuffer();
				for(UserResData res : userResDataList){
					ub.append(res.getResTreeId()).append(",");
				}
				ub.deleteCharAt(ub.length()-1);
				mav.addObject("resTreeIds",ub.toString());
			}
			mav.setViewName("secure/user/addUserForm");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return mav;
	}
	
	/**
	 * 初始化修改密码界面
	 * @return
	 */
	@RequestMapping(value="initPw.html")
	public ModelAndView init(String userId){
		ModelAndView mav = new ModelAndView();
		mav.addObject("pwModel",userService.queryUserByUserId(userId));
		mav.setViewName("secure/user/updatePw");
		return mav;
	}
	
	/**
	 * 修改用户密码
	 * @param user
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="updatePw.html")
	public @ResponseBody Map<String,Object> save(User user) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			if(user!=null){
				String userId = user.getUserId();
				String selfPassword = user.getSelfPassword();
				String oldPassword = user.getPassword();
				if(userId!=null && !"".equals(userId)){
					TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
					selfPassword = pwdEncoder.encodePassword(selfPassword, "");
					if(selfPassword.equals(oldPassword)){
						String pwString = pwdEncoder.encodePassword(user.getNewPassword(), "");
						user.setPassword(pwString);
						userService.updatePw(user);
						map.put("flag", "ok");
					}else{
						map.put("flag", "fail");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", "error");
		}
		return map;
	}

	//批量删除
	@RequestMapping(value="delUser.html")
	public @ResponseBody PageResultBean delete(String userIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				for (String s : userId) {
					userService.delUser(s);
					pr.setResult("OK");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("删除失败!");
		}
		return pr;
	}
	
	//批量重置密码
	@RequestMapping(value="resetPassword.html")
	public @ResponseBody PageResultBean resetPassword(String userIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				
				for (String s : userId) {
					User user = userService.queryUserByUserId(s);
					user.setPassword("1111");
					TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
					user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					userService.resetPassword(user);
					pr.setResult("OK");
				}	
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("重置密码失败!");
		}
		return pr;
	}
}
